import xhrAdapter from '../xhr/index.js';
import InterceptorManager from './InterceptorManager.js';
import dispatch from './dispatchRequest.js';
// 全局配置
// axios.defaults.baseURL=''

export default class Axios {
  constructor(defaultConfig) {
    this.defaults = defaultConfig;
    this.interceptor = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }
  request(config) {
    // 处理得到正确的 config
    config = mergeConfig(this.defaults, config);
    // console.log(config.validateStatus.toString());
    // 构建Promis链数组
    let promise = Promise.resolve(config);
    const chain = [dispatch, undefined];
    // 组合Promise链
    // 请求拦截器
    this.interceptor.request.forEach(interceptor => {
      chain.unshift(interceptor.fulfilled, interceptor.rejected);
    });
    // 响应拦截器
    this.interceptor.response.forEach(interceptor => {
      chain.push(interceptor.fulfilled, interceptor.rejected);
    });

    while (chain.length) {
      promise = promise.then(chain.shift(), chain.shift());
    }
    return promise;
  }
}

function mergeConfig(baseConfig, config) {
  typeof config === 'string' && (config = {url: config});
  baseConfig.baseURL && (config.url = baseConfig.baseURL + config.url);
  filterConfig(config);
  const resConfig = Object.assign({}, baseConfig, config);
  return resConfig;
}

function filterConfig(config) {
  Object.keys(config).forEach(key => {
    if (config[key] === undefined) {
      Reflect.deleteProperty(config, key);
    }
  });
}

['get'].forEach(method => {
  Axios.prototype[method] = function (url, config) {
    // 暂时忽略config中的其他属性
    return this.request({method: 'get', url, data: config.data});
  };
});
